package com.wnxy.portal.controller;

import cn.hutool.json.JSONUtil;
import com.wnxy.portal.common.constant.RedisConstant;
import com.wnxy.portal.common.result.Result;
import com.wnxy.portal.entity.Book;
import com.wnxy.portal.model.vo.BookVo;
import com.wnxy.portal.model.vo.PageVo;
import com.wnxy.portal.service.IBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/book")
@Api(tags = "图书管理")
public class BookController {
    @Autowired
    private IBookService bookService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 首页精品推荐，top10, 根据销量排行
     * 改造：因为项目启动时候已经把top10图书预热到redis的zset集合中，所以这里直接从redis获取
     */
    @GetMapping("/top10")
    @ApiOperation("首页Top10")
    public Result bookTop10() {
        // 参数1：key； 参数2：根据分值排序的开始区间；参数3：分值的最大值；
        // 参数4：获取元素的开始位置； 参数5：返回的行数
        Set<ZSetOperations.TypedTuple> set = redisTemplate.opsForZSet().reverseRangeByScoreWithScores(
                RedisConstant.BOOK_TOP10, 0, Double.MAX_VALUE, 0, 10);
        // 遍历set集合
        List<BookVo> collect = set.stream().map(data -> {
            String jsonStr = JSONUtil.toJsonStr(data.getValue());
            BookVo bookVo = JSONUtil.toBean(jsonStr, BookVo.class);
            return bookVo;
        }).collect(Collectors.toList());
        return Result.ok(collect);
    }

    /**
     * 根据typeId查询图书
     */
    @GetMapping("/findBookByType")
    @Cacheable(cacheNames = "book",key = "#typeId + '_' + #pageNum + '_' + #pageSize")
    public Result findBookByType(
            Integer typeId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize){
        PageVo<Book> pageVo = bookService.findBookByType(typeId,pageNum,pageSize);
        return Result.ok(pageVo);
    }

    /**
     * 根据图书id查询
     */
    @GetMapping("/{bookId}")
    @Cacheable(cacheNames = "book",key = "#p0")
    public Result<Book> findById(@PathVariable("bookId") Integer id){
        return Result.ok(bookService.getById(id));
    }


}










